package fi.saarinen.simulator;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Driver for the simulator that glues all the bits and pieces together.
 * 
 * @author jsaarinen
 */
public class Simulator
{
  private M68000Context context;
  
  public Simulator(int memorySizeKB, byte[] codeBytes)
  {
    this.context = new M68000Context(memorySizeKB, codeBytes);
  }
  
  /**
   * Executes the program until it is finished.
   */
  public void run()
  {
    boolean continueSimulation = true;
    while (continueSimulation)
    {
      Instruction instruction = this.context.getNextInstruction();
      if (instruction == null)
      {
        continueSimulation = false;
      }
      else
      {
        int nextProgramCounter = instruction.execute(context, this.context.getNextWord(), this.context.getProgramCounter());
        this.context.setProgramCounter(nextProgramCounter);
      }
    }
  }
  
  public static void main(String[] args) throws IOException
  {
    if (args.length < 2)
    {
      System.err.println("Usage: <code> <ram size>");
      System.exit(1);
    }
    String fileName = args[0];
    System.out.println("Loading code from " + fileName);
    FileInputStream codeStream = new FileInputStream(fileName);
    byte[] codeBytes = new byte[codeStream.available()];
    codeStream.read(codeBytes);
    int memorySizeKB = Integer.parseInt(args[1]);
    System.out.println("Using " + memorySizeKB + " of RAM");
    
    Simulator simulator = new Simulator(memorySizeKB, codeBytes);
  }
}
